<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script>
import warZoneJson from '/public/static/warZone.json' // 导入 GeoJSON
import localPoliceStation from '/public/static/localPoliceStation.json' // 导入 GeoJSON
// 3. 配置 `map3D` 地图
import mapBg from '../../../assets/img/Frame7.png' // 地图区域背景图片
import tipsBg from '../../../assets/img/tipsBg.png'
import icon from '@/assets/img/icon/map_icon.png'
import { isNotEmpty } from '@/utils' // 标记点图标
// import up_icon from '@/assets/img/icon/up.png'
export default {
  name: 'EChartsMap3D',
  props: {
    mapType: {},
    apiData: {},
    timeMode: {},
  },
  watch: {
    mapType: {
      handler() {
        setTimeout(() => {
          this.chart.dispatchAction({
            type: 'unselect',
            seriesIndex: 0,
            name: '东部战区'
          })
        }, 500)
      },
      // 深度监听
      deep: true
    },
    apiData: {
      handler(val) {
        if (!isNotEmpty(val)) return
        setTimeout(() => {
          if (!this.chart) {
            this.initMap()
          } else {
            this.changeMap()
          }
        }, 300)
      },
      immediate: true,
      deep: true
    },
    select: {
      handler(val) {
        if (!isNotEmpty(val)) return
        if (val !== 1) {
          this.chart.setOption({
            map: 'myMap',
            geo: [
              {
                name: 'myMap', select: {
                  disabled: true,
                }
              }
            ]
          })
        } else {
          this.chart.setOption({
            map: 'myMap',
            geo: [
              {
                name: 'myMap', select: {
                  disabled: false,//可以被选中
                }
              }
            ]
          })
        }
      }
    }
  },
  data() {
    return {
      chart: null,
      regionCenterMapping: {
        '东部战区': {
          center: [117.25278554715332, 40.225987265771764],
          StreetId: '11011701'
        },
        '西部战区': {
          center: [117.1314228927847, 40.103906489187935],
          StreetId: '11011702'

        },
        '南部战区': {
          center: [117.01508709392246,
            40.18502744399902],
          StreetId: '11011703'

        },
        '北部战区': {
          center: [117.09910739310074,
            40.29002765406368],
          StreetId: '110117014'
        },
      },
      regionMapping: {
        '金海湖': {
          'center': [
            117.2859986996063,
            40.23379684486204
          ]
        },
        '镇罗营': {
          'center': [
            117.16463604523766,
            40.32831968143761
          ]
        },
        '大华山': {
          'center': [
            117.0378276307371,
            40.28841003932793
          ]
        },
        '王辛庄': {
          'center': [
            117.08217167752564,
            40.210691262588014
          ]
        },
        '南独乐河': {
          'center': [
            117.1895309486979,
            40.20298940183
          ]
        },
        '峪口': {
          'center': [
            116.98259206368472,
            40.19668787939163
          ]
        },
        '大兴庄': {
          'center': [
            117.05027508246722,
            40.16027908308104
          ]
        },
        '兴谷': {
          'center': [
            117.11795810124973,
            40.17078162047833
          ]
        },
        '滨河': {
          'center': [
            117.10239878658709,
            40.14067434660611
          ]
        },
        '夏各庄': {
          'center': [
            117.18175129136657,
            40.12737113256955
          ]
        },
        '渔阳': {
          'center': [
            117.08450557472504,
            40.13437282416774
          ]
        },
        '马坊': {
          'center': [
            117.00048527554675,
            40.09726385869733
          ]
        },
        '东高村': {
          'center': [
            117.0860615061913,
            40.09656368953751
          ]
        }
      },
      areaCode: ''
    }
  },
  mounted() {
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initMap() {
      if (!this.$refs.mapContainer) return
      this.chart = this.$echarts.init(this.$refs.mapContainer)

      // 1. 注册地图
      this.$echarts.registerMap('myMap', this.mapType === 1 ? warZoneJson : localPoliceStation)
      // 2. 生成行政区中心点标记数据
      // 区域中心点数据，key 为区域名称，value 为经纬度坐标
      const regionCenterMapping = this.regionCenterMapping
      // 例如：value: [lng, lat, policeCount, change]
      const scatterData = this.apiData.map(item => {
        const mapItem = regionCenterMapping[item.areaName]
        if (mapItem) {
          return {
            name: item.areaName,
            curNum: item.curNum,
            areaCode: item.areaCode,
            tongBiBianHuaLiang: item.tongBiBianHuaLiang,
            tongQiNum: item.tongQiNum,
            huanBiNum: item.huanBiNum,
            huanBiBianHuaLiang: item.huanBiBianHuaLiang,
            selected: this.areaCode === item.areaCode,
            // 将区域中心坐标和接口数据组合起来，例如索引 2 和 3 分别代表警情量和变化量
            value: item.latitude === '0' ? [...mapItem.center] : [item.latitude, item.longitude]
          }
        }
        return null
      }).filter(item => item !== null)

      const option = {
        backgroundColor: 'transparent', // 透明背景
        animation: false,
        tooltip: {
          show: false, // 开启提示框
          trigger: 'item',
          backgroundColor: 'rgba(255, 255, 255, 1)', // 透明背景
          borderColor: '#0a1a3a',
        },
        geo: [
          {
            layoutCenter: ['50%', '50%'], // 位置
            layoutSize: '180%', // 大小
            show: true,
            map: 'myMap',
            name: 'myMap',
            roam: false,
            zoom: 0.6,
            aspectScale: 0.9,
            // layoutCenter: ['46.5%', '57%'],
            label: {
              show: true,
              color: '#fff',
            },
            // 当区域被选中时，会应用该样式

            itemStyle: {
              normal: {
                color: {
                  image: mapBg, // 设置背景图
                  repeat: 'no-repeat', // 禁止重复
                  position: 'center', // 让图片居中
                  size: '100%',
                  x: '-500',
                  y: '-500',
                },
                borderColor: '#a5bad6',
                borderWidth: 1,
              },

            },
            emphasis: {
              itemStyle: {
                areaColor: '#0077E7',
              },
            },
            zlevel: 3,
            // 开启选中模式，支持单选或多选。这里设置为单选
            selectedMode: 'single',
            data: [],
            //这个就是鼠标点击后高亮状态，地图想要展示的配置
            select: {
              disabled: false,//可以被选中
              label: {
                show: true,
                color: '#fff'
              },
              //相关配置项很多，可以参考echarts官网
              itemStyle: {
                borderColor: '#fff',
                areaColor: '#0077E7',//'rgba(59, 184, 247, 1)',
                shadowBlur: 3,
                borderWidth: 1,
                shadowOffsetX: 2,
                shadowOffsetY: 2,
                shadowColor: '#3bb8f7',
                opacity: 0.8,
              }
            }
          },
          {
            layoutCenter: ['50%', '52%'], // 位置
            layoutSize: '180%', // 大小
            map: 'myMap',
            roam: false,
            zoom: 0.6,
            aspectScale: 0.9,
            silent: true,
            itemStyle: {
              normal: {
                borderWidth: 1,
                // borderColor:"rgba(17, 149, 216,0.6)",
                borderColor: 'rgba(58,149,253,0.8)',
                shadowColor: 'rgba(172, 122, 255,0.5)',
                shadowOffsetY: 5,
                shadowBlur: 15,
                areaColor: 'rgba(5,21,35,0.1)',
              },
            },
          },
          {
            layoutCenter: ['50%', '54%'], // 位置
            layoutSize: '180%', // 大小
            map: 'myMap',
            roam: false,
            zoom: 0.6,
            aspectScale: 0.9,
            silent: true,
            itemStyle: {
              normal: {
                borderWidth: 1,
                // borderColor: "rgba(11, 43, 97,0.8)",
                borderColor: 'rgba(58,149,253,0.4)',
                shadowColor: 'rgba(58,149,253,1)',
                shadowOffsetY: 15,
                shadowBlur: 10,
                areaColor: 'transpercent',
              },
            },
          },
        ],
        series: [
          {
            name: 'myMap',
            type: 'scatter',
            coordinateSystem: 'geo',
            label: {
              color: '#fff',
              show: true,
              position: 'left',
            },
            tooltip: {
              show: false,
            },
            animation: false,
          },
          // 标记点
          {
            name: 'point',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: scatterData,
            symbol: `image://${icon}`, // 设置自定义图标
            zlevel: 4,
            symbolSize: 64, // 标记点大小
            tooltip: {
              show: true,
              backgroundColor: 'transparent',
              borderColor: 'transparent',
              shadowColor: 'transparent',
              alwaysShowContent: true, // Ensure tooltip stays visible
              formatter: (params) => {
                let slot = ``
                let slot2 = params.data.tongQiNum
                if (params.data.curNum > params.data.tongQiNum) {
                  slot = `<div style="color:#BCA555">
                      <img style="width: 8px;height: 10px; margin-right: 2px;" src="${require('@/assets/img/icon/up.png')}">${params.data.tongBiBianHuaLiang}%</div>`
                } else if (params.data.curNum < params.data.tongQiNum) {
                  slot = `<div style="color:#4FB31C">
                      <img style="width: 8px;height: 10px; margin-right: 2px;" src="${require('@/assets/img/icon/down.png')}">${params.data.tongBiBianHuaLiang}%</div>`
                } else if (params.data.curNum === params.data.tongQiNum) {
                  slot = `<div style="color:#16B3E0">持平</div> `
                }
                if (params.data.curNum > params.data.huanBiNum) {
                  slot2 = `<div style="color:#BCA555">
                      <img style="width: 8px;height: 10px; margin-right: 2px;" src="${require('@/assets/img/icon/up.png')}">${params.data.huanBiBianHuaLiang}%</div>`
                } else if (params.data.curNum < params.data.huanBiNum) {
                  slot2 = `<div style="color:#4FB31C">
                      <img style="width: 8px;height: 10px; margin-right: 2px;" src="${require('@/assets/img/icon/down.png')}">${params.data.huanBiBianHuaLiang}%</div>`
                } else if (params.data.curNum === params.data.huanBiNum) {
                  slot2 = `<div style="color:#16B3E0">持平</div> `
                }
                return `
          <div style="min-width: 162px;height:120px;padding: 14px 16px 24px;background-image:url(${tipsBg});background-size: 100% 100%;background-repeat: no-repeat;">
              <div style="padding:6px 8px;font-size: 12px;color: #F5FAFF;line-height: 1;display: flex;justify-content: space-between">
                <div style="">
                   警情量：
                </div>
                <div>  ${params.data.curNum}</div>
              </div>
              <div style="padding:6px 8px;font-size: 12px;color: #F5FAFF;line-height: 1;display: flex;justify-content: space-between;background: linear-gradient( 270deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.2) 100%);margin-top: 4px">
                <div> ${this.timeMode.mode === 1 && !this.timeMode.endTime ? '同期警情量' : '环比变化量'} ：</div>
                <div>${slot2}</div>
             </div>
              <div style="padding:6px 8px;font-size: 12px;color: #F5FAFF;line-height: 1;display: flex;justify-content: space-between;background: linear-gradient( 270deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.2) 100%);margin-top: 4px">
              <div>同期变化量：</div>
              <div>${slot}</div>
              </div>
          </div>`
              },
              position: (point, params, dom, rect, size) => {
                let x = point[0] - size.contentSize[0] / 2
                let y = point[1] - size.contentSize[1] - 20
                return [x, y]
              },
            },
            itemStyle: {
              normal: {
                color: '#ea6347',
                borderWidth: 2,
                borderColor: '#f4b391',
              },
            },
            z: 4,
          },
        ],
      }


      // 5. 监听点击事件
      this.chart.on('click', (params) => {
        let regionData = params
        // if (params.seriesType === 'map3D') {
        //   regionData = scatterData.find((item) => item.name === params.name)
        // } else if (params.seriesType === 'scatter3D') {
        //   regionData = params.data
        // }
        const areaCode = this.apiData.find((item) => {
          if (this.mapType === 1) {
            return item.areaName === regionData.name
          } else {
            return item.areaName + '所' === regionData.name
          }
        })?.areaCode

        this.$emit('regionClick', areaCode)
        // }
      })
      // 4. 渲染 ECharts
      this.chart.setOption(option)
 /*     if (this.mapType === 1) {
        scatterData.forEach((item, index) => {
          setTimeout(() => {
            this.chart.dispatchAction({
              type: 'showTip',
              seriesIndex: 1, // 针对series下第几个数据
              dataIndex: 1 // 第几个数据
            })
          }, 1000)
        })

      }*/
    },
    changeMap() {
      // 重新注册地图（使用新 geojson 数据）
      this.$echarts.registerMap('myMap', this.mapType === 1 ? warZoneJson : localPoliceStation)
      const regionCenterMapping = this.mapType === 1 ? this.regionCenterMapping : this.regionMapping
      const scatterData = this.apiData.map(item => {
        const mapItem = regionCenterMapping[`${item.areaName}`]
        if (mapItem) {
          return {
            name: item.areaName + '所',
            curNum: item.curNum,
            StreetId: mapItem.StreetId,
            tongBiBianHuaLiang: item.tongBiBianHuaLiang,
            tongQiNum: item.tongQiNum,
            // 将区域中心坐标和接口数据组合起来，例如索引 2 和 3 分别代表警情量和变化量
            value: [...mapItem.center]
          }
        }
        return null
      }).filter(item => item !== null)
      // 更新地图配置，重新设置 map 名称即可更新显示
      this.chart.setOption({
        map: 'myMap',
        series: [
          // 标记点
          {
            name: 'point',
            data: scatterData,
          },
        ],
      })
    },
    mapClick() {
      this.changeMap()
      /*this.chart.setOption({
        map: 'myMap',
        series: [
          // 标记点
          {
            name: 'point',
            data: scatterData,
          },
        ],

      })*/
    },
  },
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh; /* 适应全屏 */
}
</style>
